﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using UnityEditor.Callbacks;
using System.Reflection;
using System.Text.RegularExpressions;
using Yoozoo.UI.YGUI;

public class AssetLocation : Editor
{

    private static readonly Regex regexPath = new Regex(@"-path:(\S*)");
    private static readonly Regex regexHierarchy = new Regex(@"-hierarchy:(\S*)");
    //[OnOpenAssetAttribute(1)]
    public static bool step1(int instanceID, int line)
    {
        string name = EditorUtility.InstanceIDToObject(instanceID).name;
        Debug.Log("Open Asset step: 1 (" + name + ")");
        return false; // we did not handle the open
    }
    //[UnityEditor.Callbacks.OnOpenAsset(0)]
    static bool step0(int instanceID, int line)
    {
        //Debug.Log($"step0 {instanceID}  {line}");
        if (line < 0) return false;

        var trackInfo = GetStackTrace();

        //Debug.Log(trackInfo);
        if (string.IsNullOrEmpty(trackInfo)) return false;

        var match = regexPath.Match(trackInfo);
        if (match.Success)
        {
            var assetPath = match.Groups[1].Value;
            UnityEngine.GameObject o = AssetDatabase.LoadAssetAtPath<UnityEngine.GameObject>(assetPath);
            EditorGUIUtility.PingObject(o);
            //Selection.activeObject = o;
            AssetDatabase.OpenAsset(o);     
        }

        var matchHierarchy = regexHierarchy.Match(trackInfo);
        if (matchHierarchy.Success)
        {
            var path = matchHierarchy.Groups[1].Value;
            GameObject go = GameObject.Find(path);
            Debug.Log($"层级视图:{path}  go={go}");
            EditorGUIUtility.PingObject(go);
            Selection.activeGameObject = go;
        }





        //UnityEditorInternal.InternalEditorUtility.OpenFileAtLineExternal( "", file), lineId);
        return true;
    }

    private static string GetStackTrace()
    {
        var editorWindowAssembly = typeof(EditorWindow).Assembly;
        var consoleWindowType = editorWindowAssembly.GetType("UnityEditor.ConsoleWindow");

        var consoleWindowFieldInfo = consoleWindowType.GetField(
                            "ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);

        var consoleWindow = consoleWindowFieldInfo.GetValue(null) as EditorWindow;

        if (consoleWindow != EditorWindow.focusedWindow)
        {
            return null;
        }

        var activeTextFieldInfo = consoleWindowType.GetField(
                               "m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);

        return (string)activeTextFieldInfo.GetValue(consoleWindow);
    }


}
